package com.yunxiao.cloud.elasticsearch.controller;

import com.yunxiao.cloud.common.base.BaseResultResponse;
import com.yunxiao.cloud.elasticsearch.entity.RequestLog;
import com.yunxiao.cloud.elasticsearch.service.RequestLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

/**
 * @description: RequestLogController
 * @author: yunxiao
 * @date: 2020/1/14 10:15
 * @version: V1.0
 **/
@Api(value = "测试elasticsearch", tags = {"各种封装的测试方法"})
@RestController
@RequestMapping("elasticsearch")
public class RequestLogController {


    @Autowired
    private RequestLogService requestLogService;

    /**
     * 数据入库 Elastic
     */
    @ApiOperation(value = "数据入库", notes = "数据入库方法")
    @PostMapping("/insert")
    public BaseResultResponse insert() {
        String result = requestLogService.esInsert(10);
        return BaseResultResponse.ok(result);
    }

    /**
     * 查询全部 Elastic
     */
    @PostMapping("/findAll")
    public BaseResultResponse<Iterable<RequestLog>> findAll() {
        Iterable<RequestLog> requestLogs = requestLogService.esFindAll();
        return BaseResultResponse.ok(requestLogs);
    }

    /**
     * 根据ID修改
     *
     * @param id
     * @return
     */
    @PostMapping("/updateById/{id}")
    public BaseResultResponse updateById(@PathVariable Long id) {
        RequestLog requestLog = new RequestLog();
        requestLog.setId(id);
        requestLog.setUserName("updateName");
        String result = requestLogService.esUpdateById(requestLog);
        return BaseResultResponse.ok(result);
    }

    /**
     * 根据ID查询
     *
     * @param id
     * @return
     */
    @PostMapping("/selectById/{id}")
    public BaseResultResponse selectById(@PathVariable Long id) {
        Optional<RequestLog> requestLog = requestLogService.esSelectById(id);
        return requestLog.<BaseResultResponse>map(BaseResultResponse::ok).orElseGet(BaseResultResponse::error);
    }

    /**
     * 根据指定条件排序
     */
    @PostMapping("/selectOrder")
    public BaseResultResponse<Iterable<RequestLog>> selectOrder() {
        return BaseResultResponse.ok(requestLogService.esFindOrder());
    }

    /**
     * 多条件排序
     */
    @PostMapping("/selectOrders")
    public BaseResultResponse<Iterable<RequestLog>> selectOrders() {
        return BaseResultResponse.ok(requestLogService.esFindOrders());
    }

    /**
     * 多条件 + 范围 搜索
     */
    @PostMapping("/search")
    public BaseResultResponse<Iterable<RequestLog>> search() {
        return BaseResultResponse.ok(requestLogService.search());
    }
}
